package com.ljpz.web.controller;

import com.ljpz.sso.query.bean.User;
import com.ljpz.web.bean.Cart;
import com.ljpz.web.bean.Item;
import com.ljpz.web.bean.Order;
import com.ljpz.web.bean.PageResult;
import com.ljpz.web.interceptors.UserLoginHanderInterceptor;
import com.ljpz.web.service.*;
import com.ljpz.web.threadLocal.UserThreadLocal;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liujunchen on 2016/12/22.
 */
@RequestMapping("order")
@Controller
public class OrderController {
    @Autowired
    private UserService  userService  ;
    @Autowired
    private ItemService itemService ;
    @Autowired
    private OrderService orderService    ;
    @Autowired
    private CartService cartService ;
    @Autowired
    private CartCookieService cartCookieService;
    /**
     * 订单确认页面
     *
     * @param itemId
     * @return
     */
    @RequestMapping(value = "{itemId}",method = RequestMethod.GET)
    public ModelAndView toOrder(@PathVariable("itemId")Long itemId ){
        ModelAndView mv =   new ModelAndView("order") ;
        Item item = this.itemService.queryById(itemId) ;
        mv.addObject("item" , item)  ;
        return   mv ;
    }

    /**
     * 提交订单
     *
     *
     * 删除购物车中的内容
     *
     * 删除对应购物车中的内容
     *
     * @param order
     * @return
     */
    @RequestMapping(value = "submit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> submit(Order order ,
                                     //@CookieValue(UserLoginHanderInterceptor.COOKIE_NAME)String token
                                     HttpServletRequest request ,
                                     HttpServletResponse response ){
        Map<String,Object> result= new HashMap<String, Object>() ;
        //填充当前登录用户的信息
        User user = UserThreadLocal.get();
        order.setUserId(user.getId());
        order.setBuyerNick(user.getUsername());
        String orderId = this.orderService.submit(order)  ;
        if (org.apache.commons.lang3.StringUtils.isEmpty(orderId)){
            //订单提交失败
            result.put("status" ,  500 )  ;
        }else {
            //订单提交成功
            result.put("status",200) ;
            result.put("data",orderId) ;
            //把购物车内容删除
            result.put("deleteCartResult", this.cartService.deleteCartList(order)) ;
            //把购物车cookie内容缓存删除
            try {
                this.cartCookieService.delete(order.getOrderItems(),request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return  result   ;
    }
    @RequestMapping(value = "success" , method =  RequestMethod.GET)
    public  ModelAndView    success(@RequestParam("id")String orderId ){
        ModelAndView  mv  = new ModelAndView("success")  ;
        //订单数据
        Order  order  =  this.orderService.queryByOrderId(orderId ) ;
        mv.addObject("order"  , order )  ;
        //送货时间，当前时间向后推2天   格式：08月18日
        mv.addObject("data", new DateTime().plusDays(2).toString("MM月dd日"));
        return   mv;
    }

    /**
     * 基于购物车下单（购物车中全部商品下单）
     *
     * @return
     */
    @RequestMapping(value = "create",method = RequestMethod.GET)
    public ModelAndView  toCartOrder(@RequestParam("itemIds")String itemIds){
        String[]   itemIdArray  =   itemIds.split("\\|") ;
        ModelAndView  mv = new ModelAndView("order-cart");
        List<Cart> carts   = new ArrayList<Cart>();
        for (Cart  cart  : this.cartService.queryCartList()) {
            for (int i=0 ; i< itemIdArray.length; i++){
                if (Long.valueOf(itemIdArray[i]).equals(cart.getItemId())){
                    carts.add(cart)  ;
                }
            }
        }
        mv.addObject("carts",carts) ;
        return  mv ;
    }
    /**
     * 我的订单查询管理
     *
     */
    @RequestMapping(value = "myOrders",method =  RequestMethod.GET)
    public ModelAndView    toMyOrder(){
        ModelAndView mv  =  new ModelAndView("my-orders");
        //得到对应用户下所有订单
        PageResult<Order>  orderspages = this.orderService.queryByUserId(1,30)  ;

//        mv.addObject("orderList",orderspages.getData() ) ;
        mv.addObject("orderResultSet", orderspages )  ;
        return   mv  ;
    }
}
